<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu="{row, index, size}">
        <!--编辑-->
        <el-button text
                   type="primary"
                   icon="el-icon-edit"
                   @click="$refs.crud.rowEdit(row, index)"
                   v-if="validData(permission.dept_edit, false) && checkDeptId(row.id, row.parentId)">编辑
        </el-button>
        <!--删除-->
        <el-button text
                   type="primary"
                   icon="el-icon-delete"
                   @click="$refs.crud.rowDel(row, index)"
                   v-if="validData(permission.dept_delete, false) && checkDeptId(row.id, row.parentId)">删除
        </el-button>
        <!--新增子项-->
        <el-button text
                   type="primary"
                   icon="el-icon-plus"
                   @click.stop="handleAdd(row, index)"
                   v-if="userInfo.authority.includes('admin') && checkDeptId(row.id, row.parentId) && row.parentId=='0'">新增子项
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { add, getDept, getTreeList, remove, update } from '@/api/system/dept';
import { mapActions, mapGetters } from 'vuex';

export default {
  data() {
    return {
      form: {},
      selectionList: [],
      loading: true,
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'auto',
        calcHeight: 210,
        gridBtn: false,
        columnBtn: false,
        searchShowBtn: true,
        searchMenuSpan: 6,
        tip: false,
        tree: true,
        border: true,
        index: true,
        selection: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 350,
        column: [
          {
            label: '登录账户',
            prop: 'account',
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            rules: [{
              required: true,
              message: '请输入登录账户',
              trigger: 'blur'
            }]
          },
          {
            label: '登录密码',
            prop: 'password',
            type: 'password',
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            rules: [
              { required: true, message: '请输入登录密码', trigger: 'blur' },
              { min: 5, message: '密码长度最少为5位', trigger: 'blur' }
            ]
          },
          {
            label: '公司简称',
            prop: 'deptName',
            search: true,
            rules: [{
              required: true,
              message: '请输入公司简称',
              trigger: 'blur'
            }]
          },
          {
            label: '公司全称',
            prop: 'fullName',
            search: true,
            rules: [{
              required: true,
              message: '请输入公司全称',
              trigger: 'blur'
            }]
          },
          {
            label: '公司Logo',
            prop: 'logo',
            type: 'upload',
            dataType: 'string',
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            limit: 1,
            listType: 'picture-card',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{
              required: false,
              message: '请选择公司Logo',
              trigger: 'click'
            }]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 12,
            hide: true,
            rules: [{
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        // addBtn: this.validData(this.permission.dept_add, false),
        viewBtn: this.validData(this.permission.dept_view, false)
        // delBtn: this.validData(this.permission.dept_delete, false),
        // editBtn: this.validData(this.permission.dept_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    ...mapActions(['GetUserInfo']),
    checkDeptId(id, parentId) {
      const deptId = this.userInfo.deptId;
      return deptId === id || deptId === parentId;
    },
    handleAdd(row) {
      this.$refs.crud.modelValue.parentId = row.id;
      this.$refs.crud.rowAdd();
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();

        // 刷新用户信息
        if (row.id === this.userInfo.deptId) {
          //  刷新用户信息
          this.GetUserInfo().then(data => {
            console.log('用户信息获取成功:', data);
          }).catch(error => {
            console.error('用户信息获取失败:', error);
          });
        }
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      if (!this.validatenull(row.children)) {
        this.$message.warning('请先删除子公司');
        return;
      }

      this.$confirm('会删除公司和其所有用户，确定删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    beforeOpen(done, type) {
      this.$refs.crud.option.column.filter(item => {
        if (item.prop === 'logo') {
          // parentId为空则可以添加logo
          item.addDisplay = this.$refs.crud.modelValue.parentId === undefined;
        }
      });

      if (['edit', 'view'].includes(type)) {
        getDept(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getTreeList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        this.data = res.data.data;
        this.loading = false;
      });
    }
  }
};
</script>

<style>
</style>
